package org.luxor.common.netty.jdk.aio.client.handler;

import org.luxor.common.netty.jdk.aio.client.AsyncTimeClientHandler;
import org.luxor.commons.core.utils.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;

/**
 * 读取 服务端消息
 *
 * @author Mr.yan @date 2023/9/3
 */
public class ClientReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
    private static final Logger log = LoggerFactory.getLogger(ClientReadCompletionHandler.class);

    private AsyncTimeClientHandler attachment;

    public ClientReadCompletionHandler(AsyncTimeClientHandler attachment) {
        if (attachment != null) {
            this.attachment = attachment;
        }
    }

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        buffer.flip();
        byte[] body = new byte[buffer.remaining()];
        buffer.get(body);
        String req = new String(body, StandardCharsets.UTF_8);
        System.out.println("Now is: " + req);
        attachment.getLatch().countDown();
    }


    @Override
    public void failed(Throwable exc, ByteBuffer buffer) {
        log.error("读取对端消息，失败", exc);
        IoUtils.closeQuietly(attachment.getClientAsyncSocketChannel());
        attachment.getLatch().countDown();
    }
}
